﻿using Microsoft.Win32;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace jlinkDemo
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private string hexFilePath="";
        public MainWindow()
        {
            InitializeComponent();
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            // 创建OpenFileDialog实例
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Filter = "Hex文件|*.hex";
            openFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
            openFileDialog.Title = "选择Hex文件";
            openFileDialog.Multiselect = false;
            bool? result = openFileDialog.ShowDialog();
            if (result == true)
            {
                hexFile.Content = openFileDialog.FileName;
                hexFilePath = openFileDialog.FileName;
            }
        }

        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            if (JLinkLoader.JLINK_Open() < 0)
            {
                Console.WriteLine("Failed to open J-Link.");
                return;
            }

            // 设置目标芯片家族，例如"Cortex-M4"适用于许多STM32型号
            /*if (JLinkLoader.JLINKARM_SelectFamily("Cortex-M4") < 0) // 根据你的STM32型号调整此参数
            {
                Console.WriteLine("Failed to select target family.");
                // 可以选择是否继续执行
            }*/

            // 或者使用SetChipName直接指定芯片名称
            //if (JLinkLoader.JLINK_SetChipName("STM32F407VGTx") < 0) // 替换为你的具体芯片型号
            //{
            //    Console.WriteLine("failed to set chip name.");
            //    // 可以选择是否继续执行
            //}
            // 设置目标芯片型号
            string deviceName = "STM32F407VG"; // 目标芯片型号
            string command = $"Device = STM32F407VG";
            StringBuilder buffer = new StringBuilder(1024); // 分配大缓冲区
            int bufferSize = buffer.Capacity;
            //int result = JLinkLoader.JLINK_ExecCommand(command,buffer, bufferSize);
            try
            {
                int result = JLinkLoader.JLINK_ExecCommand(command, buffer, bufferSize);
                Console.WriteLine($"返回值: {result}, 输出: {buffer.ToString()}");
            }
            catch(Exception ex)
            {
                Console.WriteLine($"Error: {ex.Message}");
            }
            //if (result == 0)
            //{
            //    Console.WriteLine($"芯片型号设置为 {deviceName} 成功！");
            //}
            //else
            //{
            //    Console.WriteLine("芯片型号设置失败！");
            //    return;
            //}

            // 选择接口类型，例如SWD
            if (JLinkLoader.JLINK_TIF_Select(1) < 0) // 1 for SWD
            {
                Console.WriteLine("Failed to select target interface.");
                return;
            }

            // 设置J-Link的工作速度，参数为期望的速度（单位：kHz），传入0则表示自动检测最佳速度
            int desiredSpeedKHz = 4000; // 假设希望设置速度为4 MHz
            if (JLinkLoader.JLINK_SetSpeed(desiredSpeedKHz) < 0)
            {
                Console.WriteLine("Failed to set J-Link speed.");
                // 这里可以选择是否继续执行或者直接返回
            }

            // 下载HEX文件到指定地址（这里假设是0x08000000）
            //string hexFilePath = @"path\to\your\file.hex";
            uint address = 0x08000000;
            if (JLinkLoader.JLINK_DownloadFile(hexFilePath, address) < 0)
            {
                Console.WriteLine("Failed to download file.");
                return;
            }
            // 复位目标设备
            if(JLinkLoader.JLINKARM_Reset()<0)
            {
                Console.WriteLine("Failed to reset the target device.");
                return;
            }   

            // 启动目标设备
            if (JLinkLoader.JLINK_Go() < 0)
            {
                Console.WriteLine("Failed to start the target device.");
                return;
            }

            Console.WriteLine("Download and start successful.");
        }
    }
}